<template>
	<view class="modifyPassword">
		<view class="profile_form">
			<view class="form_item">
				<text class="text">原密码：</text>
				<input type="text" placeholder="请输入原密码" class="ipt" :password="true" v-model="oldPassword">
			</view>
			<view class="form_item">
				<text class="text">新密码：</text>
				<input type="text" placeholder="请输入新密码" class="ipt" :password="true" v-model="newPassword">
			</view>
			<view class="form_item">
				<text class="text">确认密码：</text>
				<input type="text" placeholder="请确认新密码" class="ipt" :password="true" v-model="twoPassword">
			</view>
			<view class="edit" @click="edit">确认</view>
		</view>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		data() {
			return {
				oldPassword: '',
				newPassword: '',
				twoPassword: '',
			}
		},
		computed: {
			...mapState('userInfo', ['userInfo'])
		},
		methods: {
			...mapMutations('userInfo', ['setStorage']),
			...mapMutations('cart', ['setshoppingCart']),
			toast(type, msg) {
				this.$refs.uToast.show({
					type: type,
					message: msg,
					duration: 1000,
					position: "top",
				})
			},
			edit() {
				if (this.oldPassword === '' || this.newPassword === '' || this.twoPassword === '') {
					return this.toast('error', '密码不能为空')
				}
				if (this.oldPassword !== this.userInfo.password) {
					return this.toast('error', '原密码输入错误')
				}
				if (this.newPassword !== this.twoPassword) {
					return this.toast('error', '两次密码输入不一致')
				}
				uni.$http.put(`/api/user/${this.userInfo.id}`, {
					name: this.userInfo.name,
					phone: this.userInfo.phone,
					password: this.newPassword
				}).then(res => {
					if (res.data.result) {
						this.toast('success', '修改成功，请重新登录')
						setTimeout(() => {
							this.setStorage('')
							this.setshoppingCart([])
							uni.reLaunch({
								url: '/pages/personalCenter/personalCenter'
							})
						}, 1000)
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.modifyPassword {
		font-size: 14px;

		.profile_form {
			padding: 0 15px;
			border-top: 1px solid #f1f1f1;

			.form_item {
				display: flex;
				align-items: center;
				padding: 20px 0;
				border-bottom: 1px solid #f1f1f1;

				.text {
					width: 23%;
				}

				.ipt {
					font-size: 14px;
				}

				.sex_radioGroup {
					.sex_radio {
						transform: scale(0.7);
					}
				}
			}

			.edit {
				font-size: 16px;
				background-color: #884e22;
				color: #fff;
				line-height: 42px;
				text-align: center;
				margin: 35px 5px;
			}
		}
	}
</style>
